package com.project.hqshorttaxi.service.impl;

import com.project.hqshorttaxi.dto.UserSettingParam;
import com.project.hqshorttaxi.entity.UserSetting;
import com.project.hqshorttaxi.mapper.UserSettingMapper;
import com.project.hqshorttaxi.service.UserSettingService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserSettingServiceImpl implements UserSettingService {

    @Resource
    private UserSettingMapper userSettingMapper;

    @Override
    public UserSetting getById(Integer id) {
        return userSettingMapper.selectByPrimaryKey(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insert(UserSetting entity) throws Exception {
        userSettingMapper.insertSelective(entity);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(UserSetting entity) throws Exception {
        userSettingMapper.updateByPrimaryKeySelective(entity);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Integer id) throws Exception {
        userSettingMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<UserSetting> list(UserSettingParam param) {
        Example example = new Example(UserSetting.class);
        Example.Criteria c = example.createCriteria();
        if (!StringUtils.isEmpty(param.getGroupName())) {
            c.andLike("groupName", "%" + param.getGroupName() + "%");
        }
        example.orderBy("createTime").desc();
        List<UserSetting> list = userSettingMapper.selectByExample(example);
        return list;
    }

    @Override
    public List<UserSetting> listByGroup(UserSettingParam param) {
        Example example = new Example(UserSetting.class);
        Example.Criteria c = example.createCriteria();
        c.andEqualTo("groupName", param.getGroupName());
        List<UserSetting> list = userSettingMapper.selectByExample(example);
        return list;
    }

    @Override
    public UserSetting getByGroupSetName(String group, String name) {
        Example example = new Example(UserSetting.class);
        Example.Criteria c = example.createCriteria();
        c.andEqualTo("groupName", group);
        c.andEqualTo("setName", name);
        List<UserSetting> list = userSettingMapper.selectByExample(example);
        return list.size() == 0 ? null : list.get(0);
    }
}
